<!--
 * @Descripttion: 我的页面
 * @version: 
 * @Author:Hui
 * @Date: 2022-11-15 15:46:41
 * @LastEditTime: 2025-07-03 09:27:08
 * @LastEditors: sueRimn
-->

<template>
  <view class="page" :style="{ paddingTop: menuHeight + 'rpx' }">

    
    <user-info :userInfo="userInfo" @checkAuth="checkAuth" />
    <!-- <vip-card /> -->
    <order-operation :userEvaluateInfo="userEvaluateInfo" :orderStatusNumber="orderStatusNumber"
      @checkAuth="checkAuth" />

    <!-- <user-phone
      v-if="showProductInfo.productId"
      :showProductInfo="showProductInfo"
    /> -->

    <center-banner :banner="banner" />

    <action-list @checkAuth="checkAuth" />

    <!-- 公共底部 -->
    <bottom-nav type='user' />
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getOrderStatusNumber,
  getOneBanner,
} from '@/api'

import productEvaluateInfo from '@/mixins/productEvaluateInfo'
import { callAppLogin, registerLoginCallback, checkIsInApp } from '@/utils/appBridge.js'


import UserInfo from './components/UserInfo.vue'
import OrderOperation from './components/OrderOperation.vue'
// import UserPhone from './components/UserPhone.vue'
import VipCard from './components/VipCard.vue'  // 会员卡
import CenterBanner from './components/CenterBanner.vue'
import ActionList from './components/ActionList.vue'

export default {
  name: 'User',
  mixins: [productEvaluateInfo],
  components: {
    UserInfo, OrderOperation,
    CenterBanner, ActionList,
    VipCard
  },
  computed: {
    ...mapGetters([
      'userInfo', 'systemInfo'
    ]),
	menuHeight() {
	  let topHeight = 0;
	  //#ifdef MP-WEIXIN
	  const { top, height } = uni.getMenuButtonBoundingClientRect();
	  topHeight = top + height;
	  //#endif
	  //#ifndef MP-WEIXIN
	  topHeight = this.systemInfo.statusBarHeight + 44 ;
	  //#endif
	  return topHeight
	}
  },
  data() {
    return {
      isShowCollectionAccount: 0,
      orderStatusNumber: {},

      banner: {},
      isInCylApp: false, // 是否在 cylApp 中
      appToken: '' // APP 返回的 token
    }
  },

  onLoad() {
    uni.hideTabBar()
    // this.loadBanner()
    this.initData()
    // 检测是否在 APP 中
    this.isInCylApp = checkIsInApp()
    // 注册 APP 登录回调
    this.registerAppLoginCallback()
  },

  onShow() {
    this.loadUserInfo()
    this.loadProductEvaluateInfo()

  },


  onPullDownRefresh() {
    // this.loadBanner()
    this.loadUserInfo()
  },

  methods: {
    checkAuth(callback) {
      if (!this.userInfo.userId) {
        // 如果在 APP 中，调用 APP 登录
        if (this.isInCylApp) {
          this.handleAppLogin()
          return
        }
        // #ifdef H5
        uni.navigateTo({ url: '/pages/login/index' })
        //#endif
        // #ifndef H5
        uni.navigateTo({ url: '/pages/auth/index' })
        //#endif
        return
      }

      callback && callback()
    },

    // 注册 APP 登录回调
    registerAppLoginCallback() {
      if (!this.isInCylApp) return
      
      registerLoginCallback((data) => {
        console.log('[User] 收到 APP 登录回调:', data)
        // 处理登录成功后的逻辑
        if (data) {
          // 显示 token 到页面
          this.appToken = token
          getApp().globalData.token = token
          // 保存 token 到本地
          uni.setStorageSync('token', token)
          // 重新加载用户信息
          this.loadUserInfo()
          // 重新加载订单数量
          this.loadOrderNum()
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          })
        }
      })
    },

    // 调用 APP 登录
    async handleAppLogin() {
      try {
        uni.showLoading({ title: '登录中...' })
        const result = await callAppLogin({
          from: 'user-center',
          timestamp: Date.now()
        })
        uni.hideLoading()
        
        console.log('[User] APP 登录成功:', result)
        
        // 处理登录结果
        if (result) {
          // 显示 token 到页面
          this.appToken = result
          // 保存 token
          uni.setStorageSync('token', result)
          getApp().globalData.token = result
          console.log("token",result)
          console.log("getApp().globalData.token",getApp().globalData.token)
          // 重新加载用户信息
          await this.$store.dispatch('user/loadUserInfo')
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('[User] APP 登录失败:', error)
        uni.showToast({
          title: error.message || '登录失败',
          icon: 'none'
        })
      }
    },

    //初始化信息
    initData() {
      // #ifdef MP_ALIPAY
      my.setNavigationBar({
        backgroundColor: '#000000', // 想使用frontColor 这个字段必填
        frontColor: '#FFFFFF' // 设置文字及状态栏电量、日期等文字颜色
      })
      //#endif
    },
    // 获取用户信息
    async loadUserInfo() {
      try {
        if (this.userInfo.userId) {
          const info = await this.$store.dispatch('user/loadUserInfo')
          if (info) {
            // this.loadOrderNum()
          } else {
            this.orderStatusNumber = {}
          }
        } else {
          this.orderStatusNumber = {}
        }
      } finally {
        uni.stopPullDownRefresh()
      }
    },

    loadBanner() {
      getOneBanner('200015').then(({ code, data }) => {
        if (code === 200) {
          this.banner = data || {}
        }
      })
    },

    loadOrderNum() {
      getOrderStatusNumber().then(({ data, code }) => {
        if (code === 200) {
          const obj = {}

          if (data && data.length) {
            data.forEach(element => {
              obj[element.logicStatus] = element.orderCount
            });
          }

          this.orderStatusNumber = obj
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  background-color: rgba(246, 247, 249, 1);
  position: relative;
  width: 100%;
  min-height: 100vh;
  background: url(https://image.chushouya.com/assets/images/home/img_bg.png) no-repeat top center, #F7F7F7;
  background-size: 100% 680rpx,100% 100%;
  padding-bottom: 150rpx;
}

.token-display {
  margin: 20rpx 32rpx;
  padding: 20rpx;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  
  .token-label {
    display: block;
    font-size: 24rpx;
    color: #666;
    margin-bottom: 10rpx;
    font-weight: 500;
  }
  
  .token-value {
    display: block;
    font-size: 22rpx;
    color: #333;
    word-break: break-all;
    line-height: 1.6;
    background: #f5f5f5;
    padding: 16rpx;
    border-radius: 8rpx;
    font-family: 'Courier New', monospace;
  }
}
</style>
